package com.leal.util

import java.text.SimpleDateFormat
import java.util.{Calendar, Date}

/**
 * @title: DateJavaUtil
 * @projectName bigdata
 * @description: DateJavaUtil
 * @author leali
 * @date 2022/5/14 17:49
 */
object DateUtil {
  /**
   * other way new SimpleDateFormat(format).format(System.currentTimeMillis())
   * @param format yyyyMMdd
   * @return
   */
  def getCurrentTime(format: String = "yyyy-MM-dd HH:mm:ss.SSS"): String = {
    new SimpleDateFormat(format).format(new Date())
//
  }

  def getCurrentDate(format: String = "yyyy-MM-dd HH:mm:ss"):String={
    new SimpleDateFormat(format).format(Calendar.getInstance().getTime)
  }

  // 传入字符串时间，返回上周几的日期
  def getLastWeek(date: String, day: Int, format: String="yyyy-MM-dd"): String = {
    val cal = Calendar.getInstance()
    cal.setTime(new SimpleDateFormat(format).parse(date))
    cal.add(Calendar.DATE, -6 + day)
    new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime())
  }
  //传入日期，获得上个月最后一天
  def getLastMonthLastDay(date: String, format: String="yyyy-MM-dd"): String = {
    val cal = Calendar.getInstance()
    cal.setTime(new SimpleDateFormat(format).parse(date))
    cal.set(Calendar.DAY_OF_MONTH, 0)
    new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime())
  }

  //格式化时间
  def formatDate(date: String, srcFormat: String="yyyy-MM-dd", destFormat: String="yyyyMMdd"): String = {
    new SimpleDateFormat(srcFormat).format(new SimpleDateFormat(destFormat).parse(date))
  }

  def splitDate(date: String): (String, String, String) = {
    val Pattern = "(\\d{4})(\\d{2})(\\d{2})".r
    date match {
      case Pattern(year, month, day) => (year, month, day)
      case _ => throw new RuntimeException("日期格式错误")
    }
  }
}
